package com.linktco.common.aop;

import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.error.RestExceptionTranslator;
import org.springblade.core.tool.api.R;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.*;
import java.sql.SQLException;
import java.util.regex.Matcher;
import static java.util.regex.Pattern.*;


/**
 * 全局异常处理
 *
 * @author Administrator
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends RestExceptionTranslator{


    @ExceptionHandler(value = SQLException.class)
    @ResponseBody
    public R<String> sqlExceptionHandler(SQLException e) {
        e.printStackTrace();
        Matcher m1 = compile("Out of range value for column '(.*?)' at row 1").matcher(e.getMessage());
        if (m1.find()){
            return R.fail(String.format("The %s data you entered is too long", m1.group(1)));
        }

        Matcher m2 = compile("Unknown column '(.*?)' in").matcher(e.getMessage());
        if (m2.find()){
            return R.fail(String.format("Unknown column %s", m2.group(1)));
        }

        return R.fail("系统内部异常,请检查填写数据是否有误！");
    }


    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public R<String> nullPointerExceptionHandler(NullPointerException e) {
        e.printStackTrace();
        return R.fail("系统内部异常NullPointer!,请检查数据是否填写完整！");
    }

    @Override
    public R handleError(HttpMessageNotReadableException e) {
        Matcher matcher = compile("from String (.*?):").matcher(e.getMessage());
        String text = "";
        while (matcher.find()) {
            text = matcher.group(1);
        }
        log.error("消息不能读取:{}", e.getMessage());
        e.printStackTrace();
        return R.fail(String.format("你填写的 %s 数据格式有误！",text));
    }
}
